<template>
  <div class="user-info-container">
    <!-- 返回按钮 -->
    <div class="back-button-container">
      <el-button type="primary" :icon="ArrowLeft" @click="goBack" class="back-button">
        返回
      </el-button>
    </div>

    <!-- 主要内容区域 -->
    <div class="user-info-content">
      <div class="user-info-card">
        <h1 class="page-title">个人信息</h1>
        <!-- 表单区域 -->
        <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="formRules"
          label-width="100px"
          class="user-form"
        >
          <el-form-item label="头像" prop="avatar">
            <el-tooltip
                class="box-item"
                effect="dark"
                content="点击更换头像"
                placement="top"
            >
              <el-avatar
                  :src="userForm.avatar || noAvatar"
                  @click="showAvatarSelection"
                  style="cursor: pointer;"
                  class="user-avatar"
              />
              <el-input v-model="userForm.avatar" type="hidden"></el-input>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
          </el-form-item>

          <el-form-item label="用户名">
            <el-input v-model="userForm.username" disabled />
          </el-form-item>

          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="userForm.sex">
              <el-radio value="男">男</el-radio>
              <el-radio value="女">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="年龄" prop="age">
            <el-input-number v-model="userForm.age" :min="1" :max="150" />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userForm.phone" placeholder="请输入手机号" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email" placeholder="请输入邮箱" />
          </el-form-item>

          <el-form-item label="新密码" prop="password">
            <el-input
              v-model="userForm.password"
              type="password"
              placeholder="不修改请留空"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="userForm.confirmPassword"
              type="password"
              placeholder="不修改请留空"
              show-password
            />
          </el-form-item>

          <el-form-item class="form-buttons">
            <el-button type="primary" @click="updateUserInfo" :loading="loading">
              保存修改
            </el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <AvatarSelection
        v-model="avatarSelectionVisible"
        :current-avatar="userForm.avatar"
        @avatar-selected="handleAvatarSelected"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft, User, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserInfo } from '@/api/user.js'
import { update } from '@/api/auth.js'
import noAvatar from "@/assets/images/no-avatar.png";
import AvatarSelection from "@/components/AvatarSelection.vue";

const router = useRouter()
const loading = ref(false)
const userFormRef = ref()
const avatarDialogVisible = ref(false)
const newAvatarFile = ref(null)

// 用户表单数据
const userForm = reactive({
  id: null,
  nickname: '',
  username: '',
  sex: '男',
  age: 18,
  phone: '',
  email: '',
  avatar: '',
  password: '',
  confirmPassword: ''
})

// 原始用户数据，用于重置
const originalUserData = reactive({})

// 表单验证规则
const formRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 150, message: '年龄必须在 1 到 150 之间', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (userForm.password && value !== userForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 200 && res.data) {
      const userData = res.data
      Object.assign(userForm, {
        id: userData.id,
        nickname: userData.nickname,
        username: userData.username,
        sex: userData.sex,
        age: userData.age,
        phone: userData.phone,
        email: userData.email,
        avatar: userData.avatar,
        password: '',
        confirmPassword: ''
      })

      // 保存原始数据用于重置
      Object.assign(originalUserData, userData)
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 更新用户信息
const updateUserInfo = async () => {
  try {
    await userFormRef.value.validate()

    loading.value = true

    // 准备更新数据
    const updateData = {
      id: userForm.id,
      nickname: userForm.nickname,
      sex: userForm.sex,
      age: userForm.age,
      phone: userForm.phone,
      email: userForm.email,
      avatar: userForm.avatar,
      username: userForm.username
    }

    // 检查是否修改了密码
    const isPasswordChanged = userForm.password && userForm.password.trim() !== ''

    // 如果修改了密码，则包含密码字段
    if (isPasswordChanged) {
      updateData.password = userForm.password
    }

    const res = await update(updateData)

    if (res.code === 200) {
      ElMessage.success('更新成功')

      // 如果修改了密码，自动退出登录
      if (isPasswordChanged) {
        ElMessage.success('密码修改成功，请重新登录')

        // 清除本地存储
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')

        // 延迟1秒后跳转到登录页
        setTimeout(() => {
          router.push('/login')
        }, 1000)

        return // 直接返回，不执行后续代码
      }

      // 更新本地存储的用户信息（非密码修改情况）
      const updatedUserInfo = { ...originalUserData, ...updateData }
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))

      // 清空密码字段
      userForm.password = ''
      userForm.confirmPassword = ''

      // 更新原始数据
      Object.assign(originalUserData, updatedUserInfo)
    } else {
      ElMessage.error(res.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  ElMessageBox.confirm('确定要重置所有修改吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    Object.assign(userForm, {
      ...originalUserData,
      password: '',
      confirmPassword: ''
    })
    userFormRef.value.clearValidate()
    ElMessage.success('已重置')
  }).catch(() => {})
}

// 显示头像选择对话框
const showAvatarDialog = () => {
  avatarDialogVisible.value = true
}


const avatarSelectionVisible = ref(false)

// 显示头像选择对话框
const showAvatarSelection = () => {
  avatarSelectionVisible.value = true
}

// 处理头像选择结果
const handleAvatarSelected = (avatarUrl) => {
  userForm.avatar = avatarUrl
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.user-info-container {
  min-height: 100vh;
  position: relative;
}

.back-button-container {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
}

.back-button {
  border-radius: 20px;
  padding: 8px 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.user-info-content {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 60px;
}

.user-info-card {
  background: var(--el-bg-color);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 600px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.page-title {
  text-align: center;
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 30px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.avatar-section {
  text-align: center;
  margin-bottom: 30px;
}

.user-avatar {
  border: 4px solid #fff;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
}

.change-avatar-btn {
  color: #667eea;
  font-weight: 500;
  transition: all 0.3s;
}

.change-avatar-btn:hover {
  color: #764ba2;
  transform: translateY(-2px);
}

.user-form {
  margin-top: 20px;
}

.user-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #2c3e50;
}

.user-form :deep(.el-input__wrapper) {
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.user-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.user-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.form-buttons {
  text-align: center;
  margin-top: 30px;
}

.form-buttons :deep(.el-form-item__content) {
  justify-content: center;
  gap: 15px;
}

.form-buttons .el-button {
  border-radius: 20px;
  padding: 10px 30px;
  font-weight: 500;
  transition: all 0.3s;
}

.form-buttons .el-button--primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
}

.form-buttons .el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.form-buttons .el-button:not(.el-button--primary) {
  border: 2px solid #ddd;
  color: #666;
}

.form-buttons .el-button:not(.el-button--primary):hover {
  border-color: #667eea;
  color: #667eea;
  transform: translateY(-2px);
}

/* 头像选择对话框样式 */
.avatar-selection {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.current-avatar {
  text-align: center;
}

.current-avatar h4 {
  margin-bottom: 15px;
  color: #2c3e50;
  font-weight: 500;
}

.avatar-upload h4 {
  margin-bottom: 15px;
  color: #2c3e50;
  font-weight: 500;
  text-align: center;
}

.avatar-upload :deep(.el-upload-dragger) {
  border-radius: 10px;
  border: 2px dashed #d9d9d9;
  transition: all 0.3s;
}

.avatar-upload :deep(.el-upload-dragger:hover) {
  border-color: #667eea;
}

.dialog-footer {
  text-align: center;
}

.dialog-footer .el-button {
  border-radius: 20px;
  padding: 8px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-info-card {
    margin: 0 10px;
    padding: 30px 20px;
  }

  .page-title {
    font-size: 24px;
  }

  .user-form :deep(.el-form-item__label) {
    width: 80px !important;
  }
}

/* 暗黑模式支持 */
@media (prefers-color-scheme: dark) {
  .user-info-card {
    background: rgba(31, 41, 55, 0.95);
    color: #f3f4f6;
  }

  .page-title {
    color: #f3f4f6;
  }

  .user-form :deep(.el-form-item__label) {
    color: #f3f4f6;
  }

  .current-avatar h4,
  .avatar-upload h4 {
    color: #f3f4f6;
  }
}
</style>
